﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.AspNetCore.Mvc.Authorization;
using Abp.Auditing;
using Abp.Web.Models;
using FwProject.Com.Dto;
using FwProject.Configuration;
using FwProject.Controllers;
using FwProject.Shop;
using FwProject.Shop.Dto;
using FwProject.ShoppingMall.Shop;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Configuration;

namespace FwProject.Web.Shop.Controllers
{
    /// <summary>
    /// 商品
    /// </summary>
    [AbpMvcAuthorize]
    public class CommodityController : FwProjectControllerBase
    {
        private readonly IShopProductAppService _shopProductAppService;
        private readonly IShopTypeAppService _shopTypeAppService;
        private readonly IShopSupplierAppService _shopSupplierAppService;
        private readonly IHostingEnvironment _env;

        private readonly IConfigurationRoot _appConfiguration;
        public CommodityController(IShopProductAppService shopProductAppService, IShopTypeAppService shopTypeAppService, IHostingEnvironment env, IShopSupplierAppService shopSupplierAppService)
        {
            _shopProductAppService = shopProductAppService;
            _appConfiguration = env.GetAppConfiguration();
            _shopTypeAppService = shopTypeAppService;
            _shopSupplierAppService = shopSupplierAppService;
            _env = env;
        }

        #region 商品管理

        /// <summary>
        /// 商品列表
        /// </summary>
        /// <returns></returns>
        public IActionResult CommodityIndex()
        {
            ViewBag.ImageUrl = _appConfiguration["ImageUrl:url"].ToString();
            return View();
        }

        /// <summary>
        /// 商品列表数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [DisableAuditing]
        [WrapResult(false, false)]//关闭ABP的返回数据封装
        public async Task<IActionResult> GetCommodityData(int page, int limit, Guid? shopTypeid, ShopProductFlag? shopProductFlag, string keyword = "")
        {
            var data = await _shopProductAppService.GetCommodityLayerDataAsync(page, limit, keyword, shopTypeid, shopProductFlag);
            return Json(data);
        }

        /// <summary>
        /// 选择类型
        /// </summary>
        /// <returns></returns>
        public IActionResult SelectType()
        {
            return View();
        }

        public async Task<IActionResult> Create(Guid typeid)
        {
            var dto = await _shopProductAppService.GetCreateDtoAsync(typeid);
            var any = await _shopTypeAppService.GetCompleteTypeNameAsync(typeid);
            ViewBag.ImageUrl = _appConfiguration["ImageUrl:url"].ToString();
            ViewBag.TypeName = string.Join(">", any);

            var suppliers = await _shopSupplierAppService.GetListAsync();
            ViewBag.Suppliers = suppliers.Select(o => new SelectListItem() { Text = o.SupplierName, Value = o.Id.ToString() });

            return View(dto);
        }
        [HttpPost]
        public async Task<IActionResult> Create(ShopProductEnterDto input)
        {
            int count = Convert.ToInt32(Request.Form["foreachItem"]);
            if (count > 0)
            {
                input.Specs = new List<SpecDto>();
                for (int i = 0; i < count; i++)
                {
                    SpecDto dto = new SpecDto();

                    dto.Specids = Request.Form["specids"].ToString().Split(",")[i];
                    dto.Specvids = Request.Form["specvids"].ToString().Split(",")[i];
                    dto.SpecvNames = Request.Form["specvnames"].ToString().Split(",")[i];
                    dto.Price = Convert.ToDecimal(Request.Form["prices"].ToString().Split(",")[i]);
                    dto.Weight = float.Parse(Request.Form["weights"].ToString().Split(",")[i]);
                    dto.Cost = Convert.ToDecimal(Request.Form["costs"].ToString().Split(",")[i]);
                    input.Specs.Add(dto);
                }
            }

            var id = await _shopProductAppService.CreateAsync(input);
            return Json(id);
        }


        public async Task<IActionResult> Edit(Guid id)
        {
            var entity = await _shopProductAppService.GetEditDtoAsync(id);

            var any = await _shopTypeAppService.GetCompleteTypeNameAsync(entity.ShopTypeid);
            ViewBag.ImageUrl = _appConfiguration["ImageUrl:url"].ToString();
            ViewBag.TypeName = string.Join(">", any);
            ViewBag.Id = id;

            var suppliers = await _shopSupplierAppService.GetListAsync();
            ViewBag.Suppliers = suppliers.Select(o => new SelectListItem() { Text = o.SupplierName, Value = o.Id.ToString() });
            return View(entity);
        }

        [HttpPost]
        public async Task<IActionResult> Edit(Guid id, ShopProductEnterDto input)
        {
            int count = Convert.ToInt32(Request.Form["foreachItem"]);
            if (count > 0)
            {
                input.Specs = new List<SpecDto>();
                for (int i = 0; i < count; i++)
                {
                    SpecDto dto = new SpecDto();
                    var skuid = Request.Form["skuid"].ToString().Split(",")[i];
                    if (string.IsNullOrEmpty(skuid))
                    {
                        dto.Id = null;
                    }
                    else
                    {
                        dto.Id = new Guid(skuid);
                    }
                    dto.Specids = Request.Form["specids"].ToString().Split(",")[i];
                    dto.Specvids = Request.Form["specvids"].ToString().Split(",")[i];
                    dto.SpecvNames = Request.Form["specvnames"].ToString().Split(",")[i];
                    dto.Price = Convert.ToDecimal(Request.Form["prices"].ToString().Split(",")[i]);
                    dto.Weight = float.Parse(Request.Form["weights"].ToString().Split(",")[i]);
                    dto.Cost = Convert.ToDecimal(Request.Form["costs"].ToString().Split(",")[i]);
                    input.Specs.Add(dto);
                }
            }

            await _shopProductAppService.ModifyAsync(id, input);

            return Json(id);
        }


        [HttpPost]
        public IActionResult UpLoadImg()
        {
            string FileServicePath = _appConfiguration["FileServicePath:TempCommodity"].ToString();
            return Json(base.UploadFile(FileServicePath));
        }
        /// <summary>
        /// 宣传图
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpLoadPropagandaImg()
        {
            string FileServicePath = _appConfiguration["FileServicePath:TempCommodityPropaganda"].ToString();
            return Json(base.UploadFile(FileServicePath));
        }

        /// <summary>
        /// 详情图
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpLoadDetailsImg()
        {
            string FileServicePath = _appConfiguration["FileServicePath:TempCommodityDetails"].ToString();
            return Json(base.UploadFile(FileServicePath));
        }
        /// <summary>
        /// 商品列表导出
        /// </summary>
        /// <param name="shopTypeid"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public async Task<IActionResult> ExportCommodity(Guid? shopTypeid, string keyword = "")
        {
            var list = await _shopProductAppService.GetExportCommodityDataAsync(keyword, shopTypeid);
            return DoExcel<ShopProductOutputDto>(list, _env);
        }
        #endregion



        [HttpGet]
        [DisableAuditing]
        [WrapResult(false, false)]//关闭ABP的返回数据封装
        public IActionResult GetSearchSuggest(string keyword = "")
        {
            var data = _shopProductAppService.GetSearchSuggestData(keyword);
            return Json(data);
        }
    }
}